package com.demo.controller;

import com.demo.common.AppConfig;
import com.demo.common.AppResult;
import com.demo.common.ResultCode;
import com.demo.exception.ApplicationException;
import com.demo.model.Article;
import com.demo.model.User;
import com.demo.services.IArticleService;
import com.demo.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author quan
 * @Description 帖子
 * @Date 2023/8/12 11:37
 */
@Api(tags = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;

    /**
     * 显示帖子列表：如果传入boardId，就显示对应版块帖子；否则显示所有帖子
     * @return
     */
    @ApiOperation("根据是否传入版块id查询对应帖子信息")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("版块Id")
                                                    @RequestParam(value = "boardId",required = false)
                                                    Long boardId){
        //0-定义返回结果
        List<Article> result;
        //1-分情况处理
        if(boardId == null){
            //调用查询所有帖子的方法：说明点击的是首页
            result = articleService.selectAll();
        }else{
            result = articleService.selectByBoardId(boardId);
        }
        //2-判断集合是否为空
        if(result == null){
            result = new ArrayList<>();//这种方式得到的集合是[]，而不是null。
        }
        //3-返回结果
        return AppResult.success(result);
    }

    /**
     * 发布帖子
     * @param request HTTP请求
     * @param boardId 版块Id
     * @param title 帖子标题
     * @param content 帖子内容
     * @return AppResult
     */
    @ApiOperation("发布帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("版块id") @RequestParam("boardId") Long boardId,
                            @ApiParam("帖子标题") @RequestParam("title")String title,
                            @ApiParam("帖子内容") @RequestParam("content")String content){
        //1-获取当前登录用户：当前登录用户就是发帖人
        HttpSession session =  request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION_INFO);
        //2-判断当前发帖人是否在禁言状态
        if(user.getState()==1){
            //用户已经禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3-构造帖子对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        //4-调用service
        articleService.create(article);
        //5-执行成功
        return AppResult.success("帖子发布成功！");
    }

    /**
     * 根据帖子Id获取帖子(用户版块)信息
     * @param id 帖子Id
     * @return AppResult<Article>
     */
    @GetMapping("/getDetails")
    @ApiOperation("获取帖子(用户版块)详情")
    public AppResult getDetails(HttpServletRequest request,
                                @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //1-参数校验
        if(id == null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-调用service
        Article article = articleService.selectById(id);
        //3-对查询结果做校验
        if(article == null){
            return AppResult.failed("帖子不存在");
        }
        //4-更新帖子浏览数（更新的是数据库的）
        articleService.updateVisitCountById(article.getId());
        //5-更新帖子浏览数（更新的是返回给前端的对象的）
        article.setVisitCount(article.getVisitCount()+1);
        //6-判断当前登录用户和帖子作者是不是同一人
        //获取登录作者
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION_INFO);
        if(user.getId()==article.getUserId()){
            //说明是同一个人
            article.setOwn(true);
        }
        //6-返回结果
        return AppResult.success(article);
    }

    /**
     * 更新帖子信息
     * @param request HTTP请求
     * @param id 帖子Id
     * @param title 帖子标题
     * @param content 帖子内容
     * @return AppResult
     */
    @ApiOperation("更新帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                       @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id,
                       @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                       @ApiParam("帖子内容") @RequestParam("content") @NonNull String content){
        //1-参数校验
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION_INFO);
        //1-1先校验用户是否被禁言
        if(user.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //1-2参数合法性
        if(id == null || id <=0 || StringUtils.isEmpty(title) || StringUtils.isEmpty(content)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //1-3校验当前登录用户和帖子作者是不是同一个人，不是的话不能更新
        //通过帖子Id获取当前编辑的帖子
        Article article = articleService.selectById(id);
        if(user.getId()!=article.getUserId()){
            //打印日志
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UNAUTHORIZED));
        }
        //1-4校验当前帖子状态是否正常
        if(article.getState() == 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //2-更新帖子
        articleService.modify(id,title,content);
        //3-返回结果
        return AppResult.success("更新成功");
    }

    /**
     * 根据帖子Id更新帖子点赞数
     * @param id 帖子id
     */
    @ApiOperation("更新帖子点赞数")
    @GetMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //1-参数校验
        if(id == null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_INFO);
        // 判断用户是否被禁言
        if (user.getState() == 1) {
            // 返回结果
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2-调用service
        articleService.updateLikeCountById(id);
        //3-不报错就返回结果
        return AppResult.success("点赞成功");

    }

    @PostMapping("/delete")
    @ApiOperation("删除帖子")
    public AppResult deleteById(HttpServletRequest request,
                           @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){

        //1-用户状态校验
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_INFO);
        if(user.getState()==1){
            // 表示用户禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2-通过id查询帖子信息
        Article article = articleService.selectById(id);
        //2-1 校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            // 表示帖子已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //2-2 校验当前登录的用户是不是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //3-调用service进行删除
        articleService.deleteById(id);
        //4-返回操作成功
        return AppResult.success();
    }

    @ApiOperation("获取用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult  getAllByUserId(HttpServletRequest request,
                                     @ApiParam("用户id") @RequestParam(value = "userId",required = false) Long userId){
        //1-判断userId是否为空
        //如果为空，从session中获取用户信息
        if(userId == null){
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION_INFO);
            //设置userId
            userId = user.getId();
        }
        //2-调用service
        List<Article> result = articleService.selectByUserId(userId);
        //3-判断是否为null
        if(result == null){
            //设置空集合
            result = new ArrayList<>();
        }
        //4-返回结果
        return AppResult.success(result);
    }
}
